package slh.myMapReduce;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.FloatWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import slh.ConSql;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.io.File;
import java.io.FileWriter;

public class TopRatedMovieDriver {

    public static void main(String[] args) throws Exception {
        // 从数据库导出电影评分数据

        if (args.length != 2) {
            System.err.println("Usage: MovieCommentAnalysis <input path> <output path>");
            System.exit(-1);
        }
        Configuration conf = new Configuration();
        Job job = Job.getInstance(conf, "Top 3 Rated Movies");

        job.setJarByClass(TopRatedMovieDriver.class);
        job.setMapperClass(TopRatedMovieMapper.class);
        job.setReducerClass(TopRatedMovieReducer.class);

        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(FloatWritable.class);

        FileInputFormat.addInputPath(job, new Path(args[0]));
        FileOutputFormat.setOutputPath(job, new Path(args[1]));

        System.exit(job.waitForCompletion(true) ? 0 : 1);
    }

    private static void exportMovieDataToFile() throws Exception {
        Connection conn = null;
        PreparedStatement stmt = null;
        ResultSet rs = null;
        FileWriter writer = null;

        try {
            conn = ConSql.getConnection();
            // 查询电影基本信息和评分
            String query = "SELECT MOVIE_ID, TITLE, SCORE, RATING_COUNT FROM Movie WHERE SCORE IS NOT NULL";
            stmt = conn.prepareStatement(query);
            rs = stmt.executeQuery();

            new File("input").mkdirs();
            writer = new FileWriter("input/movie_data.txt");

            while (rs.next()) {
                String line = String.format("%d,%s,%.1f,%d%n",
                        rs.getInt("MOVIE_ID"),
                        rs.getString("TITLE"),
                        rs.getFloat("SCORE"),
                        rs.getInt("RATING_COUNT"));
                writer.write(line);
            }
        } finally {
            if (writer != null) writer.close();
            if (rs != null) rs.close();
            if (stmt != null) stmt.close();
            if (conn != null) conn.close();
        }
    }
}
